import React, { createContext, useContext, useState, useEffect } from 'react';
import { ConfigProvider, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';

// 定义主题上下文类型
interface ThemeContextType {
  isDarkMode: boolean; // 是否为深色模式
  isEnglish: boolean; // 是否为英文语言
  toggleTheme: () => void; // 切换主题的函数
  toggleLanguage: () => void; // 切换语言的函数
}

// 创建主题上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 主题提供者组件
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  // 从本地存储中获取深色模式状态，若不存在则默认使用浅色模式
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const saved = localStorage.getItem('isDarkMode');
    return saved ? JSON.parse(saved) : false;
  });

  // 从本地存储中获取语言状态，若不存在则默认使用中文
  const [isEnglish, setIsEnglish] = useState(() => {
    const saved = localStorage.getItem('isEnglish');
    return saved ? JSON.parse(saved) : false;
  });

  // 当深色模式状态变化时，更新本地存储和全局样式
  useEffect(() => {
    localStorage.setItem('isDarkMode', JSON.stringify(isDarkMode));
    // 更新全局背景色
    document.body.style.backgroundColor = isDarkMode ? '#141414' : '#f0f2f5';
    document.body.style.color = isDarkMode ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)';
  }, [isDarkMode]);

  // 当语言状态变化时，更新本地存储
  useEffect(() => {
    localStorage.setItem('isEnglish', JSON.stringify(isEnglish));
  }, [isEnglish]);

  // 切换主题的函数
  const toggleTheme = () => {
    setIsDarkMode(!isDarkMode);
  };

  // 切换语言的函数
  const toggleLanguage = () => {
    setIsEnglish(!isEnglish);
  };

  return (
    <ThemeContext.Provider value={{ isDarkMode, isEnglish, toggleTheme, toggleLanguage }}>
      <ConfigProvider
        theme={{
          algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
          token: {
            colorBgContainer: isDarkMode ? '#1f1f1f' : '#ffffff',
            colorBgElevated: isDarkMode ? '#141414' : '#ffffff',
            colorBgLayout: isDarkMode ? '#000000' : '#f0f2f5',
            colorText: isDarkMode ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)',
          },
        }}
        locale={isEnglish ? enUS : zhCN}
      >
        {children}
      </ConfigProvider>
    </ThemeContext.Provider>
  );
};

// 自定义 Hook，用于在组件中获取主题上下文
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};